package com.aat.dizena.service;

import com.aat.dizena.bean.Question;
import com.aat.dizena.dao.QuestionDao;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Optional;

@Service
public class QuestionService
{
    @Resource
    private QuestionDao dao;


    public void save(Question s)
    {
        dao.save(s);
    }

    public void delete(Long id)
    {
        dao.deleteById(id);
    }

    public Question findById(Long id)
    {
        Optional<Question> res = dao.findById(id);
        return res.orElse(null);
    }

    public Iterator<Question> findAll()
    {
        return dao.findAll().iterator();
    }

    public Page<Question> search(String field, String value)
    {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.withQuery(QueryBuilders.matchQuery(field, value));
        return dao.search(queryBuilder.build());
    }

    public void init()
    {
        Question question1 = new Question(1L, "李白", "唐朝的伟大浪漫主义诗人");
        Question question2 = new Question(2L, "李白的角色是什么", "在王者荣耀游戏中李白是一名刺客");
        Question question3 = new Question(3L, "小米手机", "雷军的创业手机品牌就是这个");
        Question question4 = new Question(4L, "华为手机", "这个手机好用吗");
        Question question5 = new Question(5L, "苹果", "苹果手机是美国的品牌");
        Question question6 = new Question(6L, "苹果醋", "非常好喝开胃的饮品，淘宝售卖39.8一箱");
        Question question7 = new Question(7L, "中华", "来包华子OK吗");
        Question question8 = new Question(8L, "奶茶", "秋天的第一杯奶茶好喝吗");
        Question question9 = new Question(9L, "牡丹花", "洛阳城武则天的最爱花朵");
        save(question1);
        save(question2);
        save(question3);
        save(question4);
        save(question5);
        save(question6);
        save(question7);
        save(question8);
        save(question9);
    }

}
